package com.dxl.lanju.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dxl.common.consts.SysConsts;
import com.dxl.common.model.Page;
import com.dxl.common.model.RespData;
import com.dxl.common.utils.MD5;
import com.dxl.common.utils.Utils;
import com.dxl.lanju.dao.UserDao;
import com.dxl.service.common.BaseService;
import com.lanju.entity.User;

@Service
@Transactional
public class UserService extends BaseService {
	private static final Logger LOG = Logger.getLogger(UserService.class);
	@Autowired
	private UserDao userDao;
	
	public RespData save(User user) {
		User srcUser;
		if (Utils.isNotBlank(user.getId())) {
			srcUser = this.get(User.class, user.getId());
			srcUser.setLoginName(user.getLoginName());
			if (!SysConsts.SIX_STAR.equals(user.getPassword())) {
				srcUser.setPassword(MD5.crypt(user.getPassword()));
			}
			srcUser.setName(user.getName());
			srcUser.setMobile(user.getMobile());
			srcUser.setState(user.getState());
			srcUser.setCarNum(user.getCarNum());
			srcUser.setLog(user.getLog());
			srcUser.setSex(user.getSex());
		} else {
			if (this.userDao.exist(user.getLoginName())) {
				return RespData.instance(RespData.FAIL, "用户已经存在！");
			}
			srcUser = user;
			srcUser.setPassword(MD5.crypt(user.getPassword()));
		}
		super.save(srcUser);
		return RespData.instance(RespData.SUCCESS, srcUser.getId());
	}
	
	public RespData del(String[] ids) {
		if (Utils.isEmpty(ids)) {
			return RespData.instance(RespData.SUCCESS);
		} else {
			try {
				this.del(User.class, ids);
				return RespData.instance(RespData.SUCCESS);
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
				return RespData.instance(RespData.FAIL);
			}
		}
	}
	
	public RespData state(String[] ids, Integer state) {
		if (Utils.isEmpty(ids)) {
			return RespData.instance(RespData.SUCCESS);
		} else {
			try {
				Map<String, Object> values = new HashMap<String, Object>();
				values.put("state", state);
				this.update(User.class, ids, values);
				return RespData.instance(RespData.SUCCESS);
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
				return RespData.instance(RespData.FAIL);
			}
		}
	}
	
	public Page<User> list(String keyword, Integer state, Integer page, Integer rows) {
		return userDao.list(keyword, state, page, rows);
	}
}
